package com.surpassun.emall.service.impl;

import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.surpassun.emall.exception.NoSuchStoreTypeException;
import com.surpassun.emall.model.StoreType;
import com.surpassun.emall.repository.StoreTypeRepository;
import com.surpassun.emall.service.StoreTypeService;
import com.surpassun.emall.util.QueryUtil;
import com.surpassun.emall.util.StringPool;
import com.surpassun.emall.util.StringUtil;
import com.surpassun.emall.util.Validator;

/**
 *
 * @author Denis
 */
@Service
public class StoreTypeServiceImpl extends AbstractServiceImpl<StoreType> implements StoreTypeService {

	private Logger _log = LoggerFactory.getLogger(StoreTypeServiceImpl.class);
	
	@Inject
	StoreTypeRepository storeTypeRepository;
	
	public StoreTypeServiceImpl() {
		super(StoreType.class);
    }

	@Override
	public void addStoreType(String name, long parentId) throws NoSuchStoreTypeException {
		StoreType parent = super.get(parentId);
		if (Validator.isNull(parent)) {
			throw new NoSuchStoreTypeException("No parent storeType found with id : " + parentId);
		}

		StoreType type = new StoreType(name, parentId);
		storeTypeRepository.add(type);
	}

	@Override
	public void addStoreType(String name, StoreType parent) {
		if (Validator.isNotNull(parent)) {
			StoreType type = new StoreType(name, parent.getId());
			storeTypeRepository.add(type);
		}
	}

	@Override
	public void initializeStoreTypes(String[] storeTypes, StoreType parentStoreType) {
		for (String storeType : storeTypes) {
			if (Validator.isNull(parentStoreType)) {
				String[] temp = StringUtil.split(storeType, StringPool.POUND);
				if (Validator.isNotEmpty(temp) && temp.length == 2) {
					String parentStoreTypeName = temp[0];
					String[] childStoreTypes = StringUtil.split(temp[1], StringPool.AT);
					
					//Add parent store type
					StoreType type = storeTypeRepository.getSingleByField("typeName", parentStoreTypeName, QueryUtil.EQUAL);
					if (Validator.isNull(type)) {
						type = new StoreType(parentStoreTypeName, 0);
						storeTypeRepository.add(type);
						_log.info("New store type '" + parentStoreTypeName + "' added");
					}
					
					//Add child store types
					initializeStoreTypes(childStoreTypes, type);
				}
			} else {
				String typeName = parentStoreType.getTypeName() + StringPool.PERIOD + storeType;
				StoreType type = storeTypeRepository.getSingleByField("typeName", typeName, QueryUtil.EQUAL);
				if (Validator.isNull(type)) {
					type = new StoreType(typeName, parentStoreType.getId());
					storeTypeRepository.add(type);
					_log.info("New store sub-type '" + typeName + "' added");
				}
			}
		}
	}

	@Override
	public List<StoreType> getRootTypes() {
		return storeTypeRepository.getRootTypes();
	}
    
}